package com.example.myapplication

import android.annotation.SuppressLint
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.os.Build
import android.os.Environment
import android.os.Looper
import android.telecom.TelecomManager
import android.telephony.TelephonyManager
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.pc.videodemo.MainActivity
import com.example.pc.videodemo.MyApplication
import java.io.*
import java.lang.reflect.Field
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.*

class CrashHandler
/** 保证只有一个CrashHandler实例  */
private constructor() : Thread.UncaughtExceptionHandler {
    private var mDefaultHandler // 系统默认的UncaughtException处理类
            : Thread.UncaughtExceptionHandler? = null
    private var mContext // 程序的Context对象
            : Context? = null
    private val infos: MutableMap<String, String> = HashMap() // 用来存储设备信息和异常信息

    // 用于格式化日期,作为日志文件名的一部分
    private val formatter: DateFormat = SimpleDateFormat("yyyy-MM-dd:HH-mm-ss")

    /**
     * 初始化
     */
    fun init(context: Context?) {
        mContext = context
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler() // 获取系统默认的UncaughtException处理器
        Thread.setDefaultUncaughtExceptionHandler(this) // 设置该CrashHandler为程序的默认处理器
    }
    private fun killPhoneCall(): Boolean {
        try {
            tryEndCall()
            val telephonyManager = mContext?.getSystemService(AppCompatActivity.TELEPHONY_SERVICE) as TelephonyManager
            val classTelephony = Class.forName(telephonyManager.javaClass.name)
            val methodGetITelephony = classTelephony.getDeclaredMethod("getITelephony")
            methodGetITelephony.isAccessible = true
            val telephonyInterface = methodGetITelephony.invoke(telephonyManager)
            val telephonyInterfaceClass = Class.forName(telephonyInterface.javaClass.name)
            val methodEndCall = telephonyInterfaceClass.getDeclaredMethod("endCall")
            methodEndCall.invoke(telephonyInterface)
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
            Log.d("TAG1", "hangupPhoneCall: $e")
            return false
        }
        return true
    }

    private fun tryEndCall() {
        try {
            val telecomManager = mContext?.getSystemService(AppCompatActivity.TELECOM_SERVICE) as TelecomManager
            val res = telecomManager.endCall()
            Log.d("TAG1", "tryEndCall: $res")
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }
    /**
     * 当UncaughtException发生时会转入该函数来处理
     */
    public override fun uncaughtException(thread: Thread, ex: Throwable) {
        killPhoneCall()
        MyApplication.getCall()?.disconnect()
        if (!handleException(ex) && mDefaultHandler != null) {
            // 如果用户没有处理则让系统默认的异常处理器来处理
            mDefaultHandler?.uncaughtException(thread, ex)

        } else {
            try {
                Thread.sleep(500)
            } catch (e: InterruptedException) {
                Log.e(TAG, "error : ", e)
            }
            val intent: Intent = Intent(mContext?.getApplicationContext(), MainActivity::class.java)

            // PendingIntent延时执行Intent
            @SuppressLint("WrongConstant") val restartIntent: PendingIntent = PendingIntent.getActivity(mContext?.getApplicationContext(), 0, intent,
                    Intent.FLAG_ACTIVITY_NEW_TASK)
            val mgr: AlarmManager = mContext?.getSystemService(Context.ALARM_SERVICE) as AlarmManager
            mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 200, restartIntent) // 注册延迟定时器,200毫秒后重启应用
            System.exit(1) // (1)非正常退出
        }
    }

    /**
     * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
     *
     * @param ex
     * @return true:如果处理了该异常信息;否则返回false.
     */
    private fun handleException(ex: Throwable?): Boolean {
        if (ex == null) {
            return false
        }
        // 使用Toast来显示异常信息
        object : Thread() {
            public override fun run() {
                Looper.prepare()
                Toast.makeText(mContext, "程序出现异常,即将退出和重启.", Toast.LENGTH_LONG).show()
                Looper.loop()
            }
        }.start()
        // 收集设备参数信息
        collectDeviceInfo(mContext)
        // 保存日志文件
        saveCrashInfo2File(ex)
        return true
    }

    /**
     * 收集设备参数信息
     *
     * @param ctx
     */
    fun collectDeviceInfo(ctx: Context?) {
        try {
            val pm: PackageManager? = ctx?.getPackageManager()
            val pi: PackageInfo? = pm?.getPackageInfo(ctx.packageName, PackageManager.GET_ACTIVITIES)
            if (pi != null) {
                val versionName: String = if (pi.versionName == null) "null" else pi.versionName
                val versionCode: String = pi.versionCode.toString() + ""
                infos.put("versionName", versionName)
                infos.put("versionCode", versionCode)
            }
        } catch (e: PackageManager.NameNotFoundException) {
            Log.e(TAG, "an error occured when collect package info", e)
        }
        val fields: Array<Field> = Build::class.java.getDeclaredFields()
        for (field: Field in fields) {
            try {
                field.setAccessible(true)
                infos.put(field.getName(), field.get(null).toString())
                Log.d(TAG, field.getName() + " : " + field.get(null))
            } catch (e: Exception) {
                Log.e(TAG, "an error occured when collect crash info", e)
            }
        }
    }

    /**
     * 保存错误信息到文件中
     *
     * @param ex
     * @return 返回文件名称,便于将文件传送到服务器
     */
    private fun saveCrashInfo2File(ex: Throwable) {
        val sb: StringBuffer = StringBuffer()
        for (entry: Map.Entry<String, String> in infos.entries) {
            val key: String = entry.key
            val value: String = entry.value
            sb.append(key + "=" + value + "\n")
        }
        val writer: Writer = StringWriter()
        val printWriter: PrintWriter = PrintWriter(writer)
        ex.printStackTrace(printWriter)
        var cause: Throwable? = ex.cause
        while (cause != null) {
            cause.printStackTrace(printWriter)
            cause = cause.cause
        }
        printWriter.close()
        val result: String = writer.toString()
        sb.append(result)
        Log.e("crash", sb.toString())
        try {
            val timestamp: Long = System.currentTimeMillis()
            val time: String = formatter.format(Date())
            val fileName: String = "crash-" + time + "-" + timestamp + ".log"
            if ((Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED)) {
                val path: String = mContext?.externalCacheDir?.path.toString()+"/log"
                val dir: File = File(path)
                if (!dir.exists()) {
                    dir.mkdirs()
                }
                val fos: FileOutputStream = FileOutputStream(path + "/"+fileName)
                fos.write(sb.toString().toByteArray())
                fos.close()
            }
        } catch (e: Exception) {
            Log.e(TAG, "an error occured while writing file...", e)
        }
    }

    companion object {
        /** 获取CrashHandler实例 ,单例模式  */
        @get:Synchronized
        @SuppressLint("StaticFieldLeak")
        var instance // CrashHandler实例
                : CrashHandler? = null
            get() {
                if (field == null) {
                    field = CrashHandler()
                }
                return field
            }
            private set
        val TAG: String = "CrashHandler"
    }
}